package com.xiaoyu.commonlib.network;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.xiaoyu.commonlib.CommonPlug;
import com.xiaoyu.commonlib.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
 * 网络请求工具类
 * Created by jk on 2018/9/26.
 */
public class BaseNetworkManager {
    public static BaseNetworkManager mSelf;
    private OkHttpClient mHttpClient;

    public enum HTTP_REQUEST_TYPE {GET, POST, DELETE}

    ;
    private static final String NETWORK_ERROR = "-2";
    private static final String NETWORK_ERROR_DISCRIPTION = "网络请求失败";
    private static final int MSG_HTTP_REQUEST_FAILED = 1;
    private static final int MSG_HTTP_REQUEST_SUCCESS = 2;

    private HttpHandler mHandler;

    private BaseNetworkManager() {
        mHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        mHandler = new HttpHandler(Looper.getMainLooper());
    }

    public static final BaseNetworkManager getInstance() {
        if (mSelf == null) {
            mSelf = new BaseNetworkManager();
        }
        return mSelf;
    }

    public void sendRequest(final HTTP_REQUEST_TYPE type, final String url, HashMap<String, ? extends Object> param, final CommonHttpResponser listener) {
        FormBody body = covertFormBody(param);
        sendRequest(type, url, body, listener);
    }

    private void sendRequest(final HTTP_REQUEST_TYPE type, final String url, final FormBody formBody, final CommonHttpResponser listener) {
        Call call = getCall(type, url, formBody);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (listener != null) {
                    Message.obtain(mHandler, MSG_HTTP_REQUEST_FAILED,
                            new HttpFailedResponse(NETWORK_ERROR, NETWORK_ERROR_DISCRIPTION, listener)).sendToTarget();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (call.isCanceled()) {
                    onFailure(call, null);
                    return;
                }
                if (listener != null) {
                    String result = response.body().string();
                    Log.i("xiaoxue", "onResponse: code==="+getCode(result));
                    if (getCode(result).equals("y200")) {
                        Message.obtain(mHandler, MSG_HTTP_REQUEST_SUCCESS, new HttpSuccessResponse(result, listener)).sendToTarget();
                    }
//                    else if (getCode(result).equals("y402")) {//未登录
//                        TokenHelper.handleTokenExpired(new TokenHandler(type, url, formBody, listener));
//                    }
                    else {
                        Message.obtain(mHandler, MSG_HTTP_REQUEST_FAILED,
                                new HttpFailedResponse(getCode(result), result, listener)).sendToTarget();
                    }
                }
            }
        });
    }

    /**
     * 解析并获取请求响应吗
     *
     * @param result
     * @return
     */
    private String getCode(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            String code = NETWORK_ERROR + "";
            if (jsonObject.has("code")) {
                code = jsonObject.getString("code");
            }
            return code;
        } catch (JSONException e) {

        }
        return NETWORK_ERROR + "";
    }


    private Call getCall(HTTP_REQUEST_TYPE type, String url, FormBody formBody) {
        Request.Builder builder = new Request.Builder();
        String bodyString = paramsToString(formBody);
        switch (type) {
            case GET:
                url += bodyString;
                builder.url(url);
                Log.i("xiaoxue", "GET url = " + url);
                break;
            case POST:
                if (formBody == null) {
                    RequestBody body = new RequestBody() {
                        @Nullable
                        @Override
                        public MediaType contentType() {
                            return null;
                        }

                        @Override
                        public void writeTo(BufferedSink sink) throws IOException {

                        }
                    };
                    builder.url(url).post(body).build();
                    Log.i("xiaoxue", "POST url = " + url);
                } else {
                    builder.url(url).post(formBody).build();
                    Log.i("xiaoxue", "POST url = " + url + " \n formBody:  " + bodyString);
                }
                break;
            case DELETE:
                if (formBody == null) {
                    builder.url(url).delete().build();
                } else {
                    builder.url(url).delete(formBody).build();
                }
                break;
        }
        return mHttpClient.newCall(builder.build());
    }

    private String paramsToString(FormBody formBody) {
        StringBuilder stringBuilder = new StringBuilder();
        if (formBody != null) {
            for (int i = 0; i < formBody.size(); i++) {
                stringBuilder.append((i == 0) ? "" : "&");
                stringBuilder.append(formBody.encodedName(i));
                stringBuilder.append("=");
                stringBuilder.append(formBody.encodedValue(i));
            }
        }
        return stringBuilder.toString();
    }

    private FormBody covertFormBody(HashMap<String, ? extends Object> mapParams) {
        if (mapParams != null) {
            FormBody.Builder builder = new FormBody.Builder();
            Object[] keys = mapParams.keySet().toArray();
            Arrays.sort(keys);
            for (Object key : keys) {
                Object value = mapParams.get(key);
                if (value instanceof List) {
                    for (Object childValue : (List) value) {
                        builder.add((String) key, String.valueOf(childValue));
                    }
                } else {
                    builder.add(String.valueOf(key), String.valueOf(value));
                }
            }
            return builder.build();
        }

        return null;
    }


    class HttpHandler extends Handler {

        public HttpHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_HTTP_REQUEST_SUCCESS://请求成功
                    HttpSuccessResponse successResponse = (HttpSuccessResponse) msg.obj;
                    successResponse.listener.onSuccess(successResponse.result);
                    break;
                case MSG_HTTP_REQUEST_FAILED://请求失败
                    HttpFailedResponse failedResponse = (HttpFailedResponse) msg.obj;
                    failedResponse.listener.onFailed(failedResponse.errorCode, failedResponse.errorDiscription);
                    break;
            }
        }
    }

    /**
     * http请求失败响应类
     */
    class HttpFailedResponse {
        String errorCode;
        String errorDiscription;
        CommonHttpResponser listener;

        public HttpFailedResponse(String errorCode, String errorDiscription, CommonHttpResponser listener) {
            this.errorCode = errorCode;
            this.errorDiscription = errorDiscription;
            this.listener = listener;
        }
    }

    /**
     * http请求成功响应类
     */
    class HttpSuccessResponse {
        String result;
        CommonHttpResponser listener;

        public HttpSuccessResponse(String result, CommonHttpResponser listener) {
            this.result = result;
            this.listener = listener;
        }
    }

    class TokenHandler implements TokenHelper.IRequestTokenListener {
        private HTTP_REQUEST_TYPE type;
        private String url;
        private FormBody params;
        private CommonHttpResponser listener;

        public TokenHandler(HTTP_REQUEST_TYPE type, String url, FormBody params, CommonHttpResponser listener) {
            this.type = type;
            this.url = url;
            this.params = params;
            this.listener = listener;
        }

        @Override
        public void onTokenAccess() {
            //重新发送请求

            sendRequest(type, url, params, listener);
        }
    }

    /**
     * 取消所有请求操作
     */
    public void cancelAll() {
        mHttpClient.dispatcher().cancelAll();
    }

}

























